package gcosc.fun.hly.fastsso.utils;


import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import gcosc.fun.hly.fastsso.domain.Vo.LoginUser;
import gcosc.fun.hly.fastsso.result.Code;
import gcosc.fun.hly.fastsso.service.ISsoRealmService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class TokenUtil {

    @Value("${token.privateKey}")
    private String privateKey;

    private final String lastLoginId = "fast-sso:loginId:";

    private final RedisUtil redisUtil;
    private final ISsoRealmService realmService;

    public String getToken(LoginUser loginUser) {
        String token = JWT
                .create()
                .withClaim("id" ,loginUser.getId())
                .withClaim("username", loginUser.getUsername())
                .withClaim("email", loginUser.getEmail())
                .withClaim("sex", loginUser.getSex())
                .withClaim("age", loginUser.getAge())
                .withClaim("realm", loginUser.getRealm())
                .sign(Algorithm.HMAC256(privateKey));
        return token;
    }

    public LoginUser parseToken(String token) {
        try {
            DecodedJWT decodedjwt = JWT.require(Algorithm.HMAC256(privateKey))
                    .build().verify(token);
            Claim id = decodedjwt.getClaim("id");
            LoginUser loginUser = redisUtil.get(lastLoginId + id.asInt(), LoginUser.class);

            return loginUser;
        }catch (Exception e){
            Code.TOKEN_ERR("登录验证失败，请重新登录");
        }
        return null;
    }

    public String loginUser(LoginUser loginUser) {
        String token = getToken(loginUser);

        redisUtil.set(lastLoginId + loginUser.getId(), loginUser, 1000L);

        return token;
    }
}

